package com.lone.smallmovie.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class SmsCodeMaping {

	private static Log log = LogFactory.getLog(SmsCodeMaping.class);
	private static SmsCodeMaping m_curSmsCodeMaping= null;


	//定义全局短信验证码列表，所有关于短信验证都用此list验证
	private static ConcurrentHashMap<String, String> smsCodeMap=new ConcurrentHashMap<String, String>();
	
	public static SmsCodeMaping instance(){
		if (m_curSmsCodeMaping == null){
			synchronized (SmsCodeMaping.class) {
				if (m_curSmsCodeMaping == null) {
					m_curSmsCodeMaping = new SmsCodeMaping();
				}
			}
		}
		return m_curSmsCodeMaping;
	}
	
	/**
	 * 获取短信验证码列表
	 * */
	public ConcurrentHashMap getSmsCodeMapList(){
		return smsCodeMap;
	}
	
	/**
	 * 判断smsCodeMap中是否包含当前KEY
	 * @param key
	 * @return
	 */
	public boolean isContainsBySmsCodeMap(String key){
		return smsCodeMap.contains(key);
	}
	
	/**
	 * 验证短信验证码是否成功（成功：true 失败：false）
	 * */
	public boolean checkSmsCode(String smsCode){
		boolean smsCodeStatus=false;
		//如果MAP列表中存在当前SMSCODE，并且状态为0的,返回验证成功。（0：未使用 1：已使用）
		if(smsCodeMap.containsKey(smsCode) && smsCodeMap.get(smsCode).equals("0")){
			smsCodeMap.replace(smsCode, "1");
			smsCodeStatus=true;
		}
		return smsCodeStatus; 
	}
	
	/**
	 * 增加短信验证码到smsCodeMap中
	 * @param key
	 * @param value
	 */
	public void addSmsCodeMap(String key,String value){
		smsCodeMap.put(key, value);
	}
	
	/***
	 * 生成6位随机验证码，添加到MapList中以方便其他业务进行验证。
	 * @return String 短信验证码
	 */
	public String getSmsCode(){
		boolean rdmStatus = true;
		String smsCode="";
		//循环生成验证码，直到获取到新的验证码为止
		while(rdmStatus){
			//生成6位随机验证码，如：854163
			Random rdm = new Random();
			int rdmCode = rdm.nextInt(1000000);
			smsCode = String.format("%06d", rdmCode);
			if(!SmsCodeMaping.instance().isContainsBySmsCodeMap(smsCode)){
				//将当前生成的验证码放入全局mapList中
				addSmsCodeMap(smsCode, "0");
				rdmStatus=false;
			}
		}
		return smsCode;
	}

}
